package com.boot.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义的异常处理器
@ControllerAdvice
public class MyExceptionHandler implements HandlerExceptionResolver {

    /**
     * 通过操作request、response 比如跳转页面...
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return
     */
    @Override
    public ModelAndView resolveException(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            Exception ex) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("myError");
        if(ex instanceof ArrayIndexOutOfBoundsException){
            mv.addObject("errorMsg","这是数组下标越界异常(自定义的):"+ex.getMessage());
        }

        if(ex instanceof ArithmeticException){
            mv.addObject("errorMsg","这是数学异常:"+ex.getMessage());
        }

        return mv;
    }
}
